import axios from 'axios'
import store from '@/store'

//可以使用自定义配置新建一个 axios 实例
const instance = axios.create({
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  baseURL: 'http://localhost:8088',
  timeout: 3000
});

// request 请求拦截
instance.interceptors.request.use(
    config => {
        if (store.state.token) {
            config.headers['token'] = window.sessionStorage.getItem("token")
        }
        return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
)

//response响应拦截
axios.interceptors.response.use(response => {
      let res = response.data;
      console.log(res)

      if (res.code === 200) {
        return response
      } else {
        return Promise.reject(response.data.msg)
      }
    },
    error => {
      console.log(error)
      if (error.response.data) {
        error.message = error.response.data.msg
      }

      if (error.response.status === 401) {
        router.push("/login")
      }
      return Promise.reject(error)
    }
)


export default instance;
